<template>
  <div style="color: #FFFFFF;">
    <el-row><br></el-row>
    <el-row>
      <el-col span="4" offset="1">
        <el-tooltip class="item" effect="dark" content="更换头像" placement="bottom">
          <div class="avatar">
            <img v-if="userInfo.avatar" :src="userInfo.avatar" alt="avatar"
                 @click="show_history_avatars"
                 class="avatar">
            <img v-else :src="this.$store.getters.getDefaultAvatar" alt="default_avatar"
                 @click="show_history_avatars"
                 class="avatar">

            <el-dialog title="更换头像" :visible.sync="history_avatars">
              <span>
				<el-row>
					<el-tooltip class="item" effect="dark" content="上传头像" placement="left">
					<el-upload
              v-show="login_user"
              class="avatar-uploader"
              :action="postUrl"
              :accept="'image/*'"
              :headers="{Authorization: $store.getters.getToken}"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess">
                      <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
					</el-tooltip>
				</el-row>
                <el-row>
                  <el-col v-for="avatar in this.avatars" v-bind:key="avatar" class="history_avatars" offset="0"
                          span="6">
                    <div @click="use_history_avatar(avatar)">
                      <el-avatar :src=avatar.path alt=avatar shape="square" :size="100"/>
                    </div>
              </el-col>
                </el-row>
              </span>
            </el-dialog>
          </div>
        </el-tooltip>
      </el-col>
      <el-col span="4" style="background-color: #343434; padding: 20px;">
        <el-row>用户信息</el-row>
        <el-divider></el-divider>
        <el-row>用户名: {{ userInfo.username }}</el-row>
        <el-row><br></el-row>
        <el-row>邮箱: {{ userInfo.email }}</el-row>
        <el-row><br></el-row>
        <el-row v-show="login_user">
          <div class="balance">
            账户余额： {{ userInfo.balance }}
          </div>
          <el-row><br></el-row>
          <el-button class="alipay" @click="payByAlipay">
            <el-image style="width: 18px;height: 18px" :src="require('@/assets/alipay.svg')"></el-image>
            充值
          </el-button>
        </el-row>
        <el-row><br></el-row>
        <el-row>
          <el-tooltip class="item" effect="dark" content="详细信息" placement="bottom">
            <el-button icon="el-icon-more" @click="info_detail=true" circle></el-button>
          </el-tooltip>

          <el-tooltip class="item" effect="dark" content="编辑信息" placement="bottom">
            <el-button icon="el-icon-edit" @click="info_edit=true" circle=""></el-button>
          </el-tooltip>
        </el-row>
      </el-col>

      <el-col span="12" offset="1">
        <el-table
            :data="FriendsData"
            :header-cell-style="{background:'#696969',borderColor:'#CECECE',textAlign:'center', color:'#FFFFFF'}"
            :cell-style="{background:'#696969',borderColor:'#CECECE',textAlign:'center', color:'#FFFFFF'}">
          <el-table-column label="好友列表" prop="face">
            <template slot-scope="scope">
              <el-avatar :src="scope.row.face" :size="45" fit="fill" shape="square"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="name"></el-table-column>
          <el-table-column>
            <el-row>
              <el-col span="6">
                <el-tooltip class="item" effect="dark" content="详细信息" placement="top">
                  <el-button icon="el-icon-more" circle=""></el-button>
                </el-tooltip>
              </el-col>
              <el-dialog
                  title="更改好友昵称"
                  :visible.sync="friend_edit_visible">
              </el-dialog>
              <el-col offset="2" span="6">
                <el-tooltip class="item" effect="dark" content="更改昵称" placement="top">
                  <el-button icon="el-icon-edit" circle="" @click="friend_edit_visible=true"></el-button>
                </el-tooltip>
              </el-col>
              <el-dialog
                  title="是否删除好友"
                  :visible.sync="friend_delete_visible">
                <el-button @click="friend_delete_visible = false">取 消</el-button>
                <el-button type="primary" @click="friend_delete_visible = false">确 定</el-button>
              </el-dialog>
              <el-col offset="2" span="6">
                <el-tooltip class="item" effect="dark" content="删除好友" placement="top">
                  <el-button icon="el-icon-close" circle="" @click="friend_delete_visible=true"></el-button>
                </el-tooltip>
              </el-col>

            </el-row>
          </el-table-column>
        </el-table>
        <el-row><br></el-row>
        <el-row>
          <el-tooltip class="item" effect="dark" content="添加好友" placement="bottom">
            <el-button icon="el-icon-plus" circle></el-button>
          </el-tooltip>
        </el-row>
      </el-col>
    </el-row>
    <el-row><br></el-row>
    <el-divider></el-divider>
    <div v-show="login_user">
      <el-row>游戏仓库</el-row>
      <el-row><br></el-row>
      <el-row>
        <div class="depository">
          <el-row
              v-for="game in boughtGames" :key="game" :offset="index > 1 ? 3 : 0">
            <div class="game" @click="route_to_game(game)">
              <el-card>
                <el-image :src="game.picture_path" class="image" width="160" height="90"/>
                <p style="color: #000000;">{{ game.name }}</p>
              </el-card>
            </div>
          </el-row>
        </div>
      </el-row>
    </div>
    <el-drawer
        title="详细信息"
        :visible.sync="info_detail"
        direction="ltr">
      <div style="padding: 10px; color: #000000;">
        用户名：{{ userInfo.username }}
        <el-row><br></el-row>
        用户ID：{{ userInfo.id }}
        <el-row><br></el-row>
        注册邮箱：{{ userInfo.email }}
        <el-row><br></el-row>
        注册时间：
        <el-row><br></el-row>
        账户余额：{{ userInfo.balance }}
        <el-row><br></el-row>
      </div>
    </el-drawer>

    <el-drawer
        title="编辑信息"
        :visible.sync="info_edit"
        direction="ltr">
      <div style="padding: 10px; color: #000000;">
        更改用户名：
        <el-input v-model="userInfo.username"></el-input>
        <el-button type="primary" round @click="update_userInfo">确定</el-button>
<!--        <el-row><br></el-row>-->
<!--        更改ID：-->
<!--        <el-input v-model="new_user_ID"></el-input>-->
<!--        <el-row><br></el-row>-->
      </div>
    </el-drawer>
  </div>
</template>

<style scoped>


.depository {
  background-color: #696969;
  padding: 10px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.game {
  padding: 10px;
  margin: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  background-color: black;
}
</style>

<script>
import {mapActions} from "vuex";
import baseUrl from "@/api/baseUrl";
import {
  getHistoryAvatar,
  getUserInfoById,
  useHistoryAvatar,
  selectBought,
  getUserInfo,
  updateUserInfo
} from "@/api/user";
import {top_up_alipay} from "@/api/pay";

export default {
  data() {
    return {
      postUrl: baseUrl + "info/uploadAvatar",
      history_avatars: false,
      avatars: {},
      userInfo: {},
      friend_delete_visible: false,
      friend_edit_visible: false,
      info_detail: false,
      info_edit: false,
      FriendsData: [
        {
          face: require("@/assets/avatars/avatar1.png"),
          name: "嘤骑士",
          condition: "1"
        },
        {
          face: require("@/assets/avatars/avatar2.jpg"),
          name: "dust",
          condition: "2"
        },
        {
          face: require("@/assets/avatars/avatar2.jpg"),
          name: "dust",
          condition: "2"
        }],
      boughtGames: [
        {
          img: require("@/assets/1.jpg"),
          name: "game"
        },
        {
          img: require("@/assets/4.jpg"),
          name: "game"
        },
        {
          img: require("@/assets/5.jpg"),
          name: "game"
        },
        {
          img: require("@/assets/5.jpg"),
          name: "game"
        },
        {
          img: require("@/assets/4.jpg"),
          name: "game"
        },
        {
          img: require("@/assets/5.jpg"),
          name: "game"
        },
        {
          img: require("@/assets/5.jpg"),
          name: "game"
        },
        {
          img: require("@/assets/5.jpg"),
          name: "game"
        },
        {
          img: require("@/assets/4.jpg"),
          name: "game"
        },
        {
          img: require("@/assets/5.jpg"),
          name: "game"
        },
        {
          img: require("@/assets/5.jpg"),
          name: "game"
        }
      ],
      imgsrc: require("@/assets/1.jpg"),
    }
  },
  computed: {
    login_user: function () {
      return this.$route.query.id == null || this.$route.query.id == this.$store.getters.getId;
    }
  },
  // 在界面转到当前界面时进行用户信息检索
  mounted() {
    // 获取token信息
    // 在开启网页时，user_bar里面会验证本地存储的token
    // 如果token验证成功会保存在store里
    if (this.$store.getters.getToken) {
      // 如果query传入要看的用户的信息且不是登录用户
      // 不传入默认展示登录用户的信息
      if (!this.login_user) {
        getUserInfoById(this.$store.getters.getToken, this.$route.query.id).then(response => {
          let code = response.code;
          console.log(code)
          if (code == 200) {
            console.log(response.data.data);
            this.userInfo = response.data.data.userInfo;
            this.userInfo.avatar = baseUrl + this.userInfo.avatar.slice(1)
            // this.setUserInfo(response.data.data.userInfo);
          } else {
            this.$router.push('/')
            this.$alert('用户信息获取错误')
          }
        })
      } else {
        // 看登录用户的信息
        getUserInfo(this.$store.getters.getToken).then(response => {
          let code = response.data.code;
          if (code == 200) {
            // console.log(response.data.data.userInfo)
            this.setUserInfo(response.data.data.userInfo);
            this.userInfo = response.data.data.userInfo;
            // this.$alert(this.userInfo)
            this.userInfo.avatar = baseUrl + this.userInfo.avatar.slice(1)
          } else {
            this.$router.push('/')
            this.$alert('用户信息获取错误')
          }
        })

        selectBought(this.$store.getters.getToken, 0, 20).then(response => {
          let code = response.data.code;
          if (code == 200) {
            console.log(response.data.data.records)
            this.boughtGames = response.data.data.records;
            for (let i = 0; i < this.boughtGames.length; i++) {
              this.boughtGames[i].picture_path = baseUrl + this.boughtGames[i].picture_path.slice(1);
            }
          } else {
            console.log(response);
            this.$alert('游戏列表获取错误')
          }
        })
      }
    } else {
      this.setToLogin(true)
      this.$router.push('/')
      this.$alert('未登录')
    }
  },
  methods: {
    ...mapActions(["setUser", "setAvatar", "setBalance", "setUsername", "setToLogin", "setAvatar", "setUserInfo"]),
    request_history_avatars() {
      getHistoryAvatar(this.$store.getters.getToken).then(response => {
        let code = response.data.code
        if (code == 200) {
          this.avatars = response.data.data
          for (let i = 0; i < this.avatars.length; i++) {
            this.avatars[i].path = baseUrl + this.avatars[i].path.slice(1)
          }
        } else {
          this.$alert('未知错误')
        }
      })
    },
    show_history_avatars() {
      // this.$set(this.avatars, "b", "a")
      if (this.login_user) {
        this.request_history_avatars()
        this.history_avatars = !this.history_avatars;
      }
    },
    use_history_avatar(avatar) {
      if (this.login_user) {
        if (avatar == "") {
          // this.uploadImg();
        }
        useHistoryAvatar(this.$store.getters.getToken, avatar.avatarId).then(response => {
          let code = response.data.code;
          if (code == 200) {
            this.setAvatar(avatar.path)
            this.setAvatar(avatar.path);
          } else {
            this.$alert('出错，请重试')
          }
        })
      }
      // console.log(avatar)
      // this.setAvatars(avatar);
      this.history_avatars = false
    },
    handleAvatarSuccess(res, file) {
      // res表示后端的返回值，其中应包含文件上传后的url路径
      // console.log(res);
      this.setAvatar(baseUrl + res.data.avatar.slice(1))
      // file表示这个上传文件本身
      console.log(file);
      //   this.setAvatars(baseUrl+avatar);
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      const isLt10M = file.size / 1024 / 1024 < 10;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt10M;
      // return isJPG && isLt2M;
    },
    // 游戏跳转方法
    route_to_game(item) {
      // console.log(id)
      this.$router.push({path: '/game', query: {id: item.id}})
    },
    payByAlipay() {
      top_up_alipay(this.$store.getters.getToken, 2).then(response => {
        console.log(response)
      })
    },
    update_userInfo() {
      updateUserInfo(this.$store.getters.getToken, this.userInfo).then(response => {
        let code = response.data.code;
        if (code == 200) {
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          })
          location.reload();
        }
      })
    }
  },
}
</script>
